import MSData
import WorkerMSAPI
import WorkerPCNFirebird
import MSLogger
import MSDBTemplates
import MSConfig

import time
import os
import sys
import heartbeating

heartbeat = heartbeating.HeartbeatListener(17203)
heartbeat.start()

MSLogger.logInit('C:\\safe\\ms.wapi.log', 5, True)
MSLogger.logInfo('ms driver started')

reader = WorkerMSAPI.Worker()
reader.connect()

objects = MSConfig.readObjectsConfig('api_objects.cfg')
writer = WorkerPCNFirebird.Worker('192.168.0.121:C:\\pcn6\\data\\DATA.GDB', 'SYSDBA', 'masterkey')

for o in objects:
    o.enableOfflineCritical = False

try:
    while True:
        reader.readEventsPGSM(objects)
        reader.readEventsContactId(objects)
        writer.writeEventsStatic(objects)
        #for o in objects:
        #    print o.objectPCNId, len(o.eventsPGSM), len(o.eventsContactId)
        reader.finalyze(objects)
        
        time.sleep(15)
except KeyboardInterrupt:
    MSLogger.logError('ms daemon stopped')
    heartbeat.stop()
    #os.unlink('C:\\safe\\ms.pid')
except Exception, err:
    shr = str(err)[0:100]
    MSLogger.logError('ms driver fatal error: %s' % (str(err)))
    heartbeat.stop()
    #os.unlink('C:\\safe\\ms.pid')

